<template>
  <div class="wrap"  v-loading="loading">
    <el-card class="header-card">
      <div class="item">
        <p class="font-bold">采购单号：{{procureNo}}</p>
        <p>制单时间：{{createTime}}</p>
        <p>状态：{{ procureStatusStr }}</p>
      </div>
    </el-card>
    <div class="header">

    </div>
    <div class="content">
      <el-table
        ref="tableData"
        :data="tableData"
        :span-method="objectSpanMethod"
        border
      >
        <el-table-column
          prop="selection"
          align="center"
          width="55"
        >
          <template #header >
            <el-checkbox v-model="selectAll" @change="changeSelectAll" :indeterminate="isIndeterminate" :disabled="order1688List.length === 0"></el-checkbox>
          </template>
          <template slot-scope="{row}">
            <el-checkbox @change="selectOrder(row)" :value="selectedRow.indexOf(row.order1688) !== -1" :disabled="row.orderStatus !== 0" ></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
          prop="order1688"
          label="1688订单号"
          align="center"
          min-width="200"
        >
          <template slot-scope="{row}">
            <diy-link @click="jumpOrder1688Info(row)">{{row.order1688}}</diy-link>
            <br>
            <template>
              <el-tag type="danger" size="small" effect="dark" v-if="row.tipsType === 1">待改价</el-tag>
              <el-tag type="success" size="small" effect="dark" v-if="row.tipsType === 2">已改价</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderId"
          label="Mercado 订单"
          align="center"
          min-width="200"
        >
          <template slot-scope="{row}">
            <diy-link @click="jumpOrderInfo(row)">{{row.orderId}}</diy-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsImage"
          label="封面"
          align="center"
          width="120"
        >
          <template slot-scope="{row}">
            <img :src="row.order.image" width="85px" alt="">
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsTitle"
          label="标题"
          align="left"
          min-width="300"
        >
          <template slot-scope="{row}">
            <el-tooltip class="item" effect="dark" :content="row.order.title" placement="top">
              <div class="goods-title hidden-2">
                {{row.order.title}}
              </div>
            </el-tooltip>

            <div class="goods-SKU-info hidden-1" v-if="row.order.attributes && row.order.attributes.length > 0">
              <span
                v-for="attr in row.order.attributes"
                :key="attr.name"
                class="attr"
              >
                {{attr.name}} : {{attr.value}}
                <span class="attr-link"> | </span>
              </span>
            </div>
          </template>

        </el-table-column>

        <el-table-column
          prop="goodsId"
          label="Listing ID与SKU"
          align="center"
          min-width="200"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            {{row.order.goodsId}} {{row.order.variationSku ? `(${row.order.variationSku})` : ''}}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNum"
          label="订单需求量"
          align="center"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="packageType"
          label="包装服务"
          align="center"
          min-width="100"
        >
          <template slot-scope="{row}">
            <template v-if="row.packageType">
              <el-tag type="danger" style="font-size: 13px">
                {{ getPackageTypeStr(row.packageType)}}
              </el-tag>
            </template>
            <template v-else>-</template>
          </template>
        </el-table-column>
        <el-table-column
          prop="supplierLoginId"
          label="供应商"
          align="center"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="{row}">
            {{row.supplierLoginId ? row.supplierLoginId : '-'}}
            <template v-if="row.supplierLoginId">
              <br>
              <supplier-relation-tag :supplier-relation="row.supplierRelation"></supplier-relation-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="aliGoods"
          label="采购货源"
          align="left"
          min-width="300"
        >
          <template slot-scope="{row}">
            <ali-goods :ali-goods="row.aliGoods"></ali-goods>
          </template>
        </el-table-column>
        <el-table-column
          prop="flow"
          label="采购类型"
          align="center"
          min-width="100"
        >
          <template slot-scope="{row}">
            <template v-if="row.flow === 'general'">
              批发采购
            </template>
            <template v-else-if="row.flow === 'fenxiao'">
              一件代发
            </template>
            <template v-else>
              -
            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="quantity"
          label="本次采购量"
          align="center"
          min-width="100"
        >
        </el-table-column>
        <el-table-column
          prop="itemAmount"
          label="商品金额（元）"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="shippingFee"
          label="运费金额（元）"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="totalAmount"
          label="总额（元）"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="statusStr"
          label="状态"
          align="center"
          min-width="100"
        >
        </el-table-column>
      </el-table>
    </div>

    <div class="card">
      <el-card class="footer-card">
        <div class="item">
          <p class="text1">商品金额：<span class="font-bold">{{ sumProductPayment }} 元</span></p>
          <p class="text1">运费金额：<span class="font-bold">{{ sumShippingFee }} 元</span></p>
          <p class="text2" style="margin-bottom: 30px">总计：<span class="font-bold font-red"> {{sumTotalAmount}} 元</span></p>
          <p class="text1 font-red">
            如需协商商品单价、运费等问题，请前往l688平台联系供应商处理完毕后再返回操作支付
          </p>
        </div>
      </el-card>
    </div>

    <div class="season" style="margin-left: -12px" v-if="stickerData.length > 0 && false">
      <el-row :gutter="24">
        <el-col :span="24" >
          <el-col :span="8">
            <h4 class="title">物流信息</h4>
          </el-col>
        </el-col>
        <el-col :span="24">
          <el-col :span="8" v-for="stickerItem in stickerData" :key="stickerItem.order1688">
            <el-card shadow="hover" class="card-goods-origin">
              <order1688-tag class="card-tag"></order1688-tag>
              <div class="goods-origin-header">
                <span class="title">订单号：{{ stickerItem.order1688 }}</span>
              </div>
                <div class="goods-origin-header">
                  <span class="title">{{ stickerItem.express.expName }}（{{stickerItem.express.deliveryNo}}）</span>
                </div>
                <div class="goods-origin-content">
                  <div class="logistics">
                    <div
                      class="logistics-item"
                      v-for="(item,index) in stickerItem.express.list"
                      :key="'expressList_' + index"
                    >
                      <p class="time">{{ item.time }}</p>
                      <p class="text">{{ item.status}}</p>
                    </div>

                  </div>
                </div>

            </el-card>
          </el-col>
        </el-col>

      </el-row>
    </div>

    <div class="footer" :style="{
          top:fixedTopHeight,
        }">
      <div class="left">
        <el-button @click="backList">返 回</el-button>
      </div>
      <div class="right">
        <template v-if="procureStatus === 0">
          <div style="display: inline" class="mgr20">总计：<span class="font-red font-bold">{{sumTotalAmount}} 元</span></div>
          <el-button type="warning" @click="cancelOrder" :disabled="selectedRow.length === 0" :loading="orderLoading">取消采购</el-button>
          <el-button type="danger" @click="goPay" :disabled="selectedRow.length === 0" :loading="orderLoading">去支付</el-button>
        </template>

      </div>
    </div>

  </div>
</template>

<script>
import {cancelOrder, getOrderPayUrl, getProcureOrderInfo} from "@/api/procure";
import AliGoods from "@/views/procure/components/aliGoods.vue";
import {deepCopy} from "@/utils";
import Order1688Tag from "@/components/Tag/Order1688Tag.vue";
import stickerList from "@/views/order/stickerList.vue";
import SupplierRelationTag from "@/views/procure/components/supplierRelationTag";
import {getPackageTypeStr} from "@/utils/order";

export default {
  name: "procureOrderInfo",
  components: {SupplierRelationTag, Order1688Tag, AliGoods},
  computed:{
    stickerList() {
      return stickerList
    },
    // 表格数据
    tableData(){
      const data = [];
      this.data.forEach(item=>{
        let orderNum = 0; // 订单需求量
        if(item.order1688){
          this.data.forEach(_item=>{
            // 没有对应的阿里商品
            if(_item.order1688 && _item.order1688 === item.order1688){
              orderNum += 1;
            }
          })
        }

        const obj = deepCopy(item);
        obj.orderNum = orderNum
        data.push(obj);
      })
      return data;
    },
    // 计算要合并的字段
    mergeCell(){
      const mergeObj = {};
      // 根据order1688合并的字段
      const order1688Arr = [
        'selection',
        'order1688',
        'orderNum',
        'shippingFee',
        'totalAmount',
        'orderStatusStr',
        'statusStr',
        'supplierLoginId',
        'flow'
      ];

      // 根据规格id合并的字段
      const specIdArr = [
        'aliGoods', //
        'minOrderQuantity', //
        'quantity', //
        'itemAmount',
        'packageType'
      ];

      order1688Arr.forEach(key=>{
        mergeObj[key] = [1];
      })
      specIdArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let order1688Key = 0;
      let specIdKey = 0;
      this.tableData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据1688 合并
        if(item.order1688 && item.order1688 === this.tableData[index - 1].order1688){
          order1688Arr.forEach(key=>{
            mergeObj[key][order1688Key] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          order1688Key = index; // 记录当前行
          order1688Arr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }

        // 根据供应商id 合并
        if(item.specId && this.tableData[index - 1].specId === item.specId){
          specIdArr.forEach(key=>{
            mergeObj[key][specIdKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          specIdKey = index; // 记录当前行
          specIdArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    // 全选不定式
    isIndeterminate(){
      if(this.selectedRow.length === 0){
        return false;
      }
      if(this.selectAll){
        return false
      }
      return true
    },
    // 全部商品金额
    sumProductPayment(){
      let sumProductPayment = 0;
      this.selectedRow.forEach(order1688 =>{
        this.tableData.some(item=>{
          if(item.order1688 === order1688){
            sumProductPayment = this.$cal.accAdd(sumProductPayment,item.sumProductPayment)
            return true;
          }
        })
      })
      return sumProductPayment;
    },
    // 总运费
    sumShippingFee(){
      let shippingFee = 0;
      this.selectedRow.forEach(order1688 =>{
        this.tableData.some(item=>{
          if(item.order1688 === order1688){
            shippingFee = this.$cal.accAdd(shippingFee,item.shippingFee)
            return true;
          }
        })
      })
      return shippingFee;
    },
    // 总金额
    sumTotalAmount(){
      let totalAmount = 0;
      this.selectedRow.forEach(order1688 =>{
        this.tableData.some(item=>{
          if(item.order1688 === order1688){
            totalAmount = this.$cal.accAdd(totalAmount,item.totalAmount)
            return true;
          }
        })
      })
      return totalAmount;
    },
  },
  data(){
    return {
      procureNo: '',
      procureStatus: -1,
      procureStatusStr: '',
      data: [],
      createTime: '',
      loading: false,
      order1688List: [], // 所有的1688订单
      selectedRow: [], // 已选择的订单
      selectAll: true, // 是否全选
      orderLoading: false,
      stickerData: [], // 贴单的物流信息
      fixedTopHeight: '0',
      loop: false,
      timer: null
    }
  },
  created() {
    window.addEventListener("scroll", this.fixedTopHeightFunc);
    this.fixedTopHeightFunc()
    this.procureNo = this.$route.query.procureNo || ''
    if(!this.procureNo){
      this.$errorMessage('参数缺失')
      this.$router.go(-1)
      return;
    }

    this.getData()
  },
  beforeDestroy(){
    if(this.loop){
      clearInterval(this.timer)
    }
  },
  methods:{
    getPackageTypeStr,
    // 获取数据
    getData(){
      this.loading = true
      this.order1688List = [];
      getProcureOrderInfo(this.procureNo)
        .then(res=>{
          this.loading = false
          this.data = deepCopy(res.data)
          this.data.forEach(item=>{
            if(item.orderStatus === -1){
              return;
            }
            if(item.order1688){
              if(this.order1688List.indexOf(item.order1688) === -1){
                if(item.orderStatus === 0){
                  this.order1688List.push(item.order1688)
                }
                if(this.selectedRow.indexOf(item.order1688) === -1){
                  this.selectedRow.push(item.order1688)
                }

              }
            }
          })
          this.createTime = res.info.createTime;
          this.stickerData = res.info.stickerData;
          this.procureStatus = res.info.procureStatus;
          this.procureStatusStr = res.info.procureStatusStr;
        })
    },
    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if(this.mergeCell[column.property]){
        if(this.mergeCell[column.property][rowIndex]) {
          return [this.mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    selectOrder(row){
      const order1688 = row.order1688;
      const index = this.selectedRow.findIndex(item => item === order1688)
      if(index === -1){
        this.selectedRow.push(order1688)
      }else{
        this.selectedRow.splice(index,1)
      }
      if(this.selectedRow.length === this.order1688List.length){
        this.selectAll = true;
      }else if(this.selectedRow.length !== 0){
        this.selectAll = false;
      }else if(this.selectedRow.length === 0){
        this.selectAll = false;
      }

    },
    // 改变全选
    changeSelectAll(){
      if(this.selectAll){
        this.order1688List.forEach( order1688 =>{
          if(this.selectedRow.indexOf(order1688) === -1){
            this.selectedRow.push(order1688)
          }
        })
      }else{
        // 取消全选
        this.order1688List.forEach( order1688 =>{
          const index = this.selectedRow.indexOf(order1688)
          if(index !== -1){
            this.selectedRow.splice(index,1)
          }
        })
      }
    },
    // 返回列表页
    backList(){
      this.$router.push({
        name: 'procureOrderList'
      })
    },
    // 取消采购
    cancelOrder(){
      if(this.selectedRow.length === 0){
        return;
      }
      const postData = {
        order1688List: this.selectedRow,
      };
      this.orderLoading = true;
      cancelOrder(postData)
        .then(res=>{
          this.orderLoading = false;
          if(res.error === 0){
            this.$successMessage('取消成功')
            this.loopGetData()
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 去支付
    goPay(){
      if(this.selectedRow.length === 0){
        return;
      }
      const postData = {
        order1688List: this.selectedRow,
      }
      this.orderLoading = true;
      getOrderPayUrl(postData)
        .then(res=>{
          this.orderLoading = false
          if(res.error !== 0){
            this.$errorMessage(res.message)
          }else{
            window.open(res.data.payUrl,'_blank')
            this.loopGetData()
          }
        })
    },
    jumpOrder1688Info(row){
      const href = `https://trade.1688.com/order/new_step_order_detail.htm?orderId=${row.order1688}`;
      window.open(href,'_blank')
    },
    jumpOrderInfo(row){
      const { href } = this.$router.resolve({
        name: 'orderInfo',
        query: {
          orderId: row.orderId
        }
      })
      window.open(href,'_blank')

    },
    // 计算屏幕的高度
    fixedTopHeightFunc(){
      let windowH = window.innerHeight;
      let windowY = window.scrollY;
      this.fixedTopHeight = (windowH - 157 + windowY) + 'px';
    },
    // 定时去获取数据 如果数据有变化 刷新页面
    loopGetData(){
      if(this.loop){
        return;
      }
      this.loop = true
      // 每3秒请求一次
      this.timer = setInterval(()=>{
        getProcureOrderInfo(this.procureNo,true)
          .then(res=>{
            if(res.error !== 0){
              clearInterval(this.timer)
              this.$router.push({
                name: 'procureOrderList',
              })
              return;
            }
            if(res.data.length === 0){
              clearInterval(this.timer)
              this.$router.push({
                name: 'procureOrderList',
              })
              return;
            }
            if(res.data.length !== this.data.length){
              clearInterval(this.timer)
              this.$router.go(0); // 刷新当前页面
              return;
            }
            res.data.forEach((item,index)=>{
              if(item.statusStr !== this.data[index].statusStr){
                clearInterval(this.timer)
                this.$router.go(0); // 刷新当前页面
                return;
              }
            })
          })
      },3000)

    }
  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 10px 30px 80px;
  height: auto;
  min-height: 100vh;
  .header{
    display: flex;
    justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .header-card{
    font-size: 14px;
    background-color: rgba(242, 242, 242, 1);
    p{
      margin: 10px 0;
      padding: 0;
    }
    .font-bold{
      font-weight: bold;
    }
    .true-number{
      color: #FF0000;
      font-weight: 600;
    }
  }
}
.footer-card{
  text-align: right;
  background-color: rgba(242, 242, 242, 1);
  font-size: 14px;
  p{
    margin: 10px 0;
    padding: 0;
  }
  .text1{
    font-size: 13px;
    color: #767676;
  }
  .text2{
    font-size: 20px;
    color: #333333;
  }
  .font-red{
    color: #FF0000;
  }
}
.font-bold{
  font-weight: 650;
}
.font-red{
  color: #FF0000;
}
.footer{
  height: 80px;
  //width: calc(100% - 60px);
  //position: absolute;
  line-height: 80px;
  margin-top: 30px;
  border-top: 1px solid #CCCCCC;
  //position: fixed;
  display: flex;
  justify-content: space-between;
  position: absolute;
  width: calc(100% - 60px);
  background-color: #ffffff;
  .left{

  }
  .right{

  }
}
.card-goods-origin{
  position: relative;
  font-size: 13px;
  .card-tag{
    position: absolute;
    right: 0;
    top: 0;
  }
  .goods-origin-header{
    margin-bottom: 10px;
    .title{
      font-weight: 400;
      font-style: normal;
      font-size: 14px;
    }
  }
  .goods-origin-content{
    .goods-info{
      display: inline-block;
      .goods-title{
        font-weight: 500;
        font-style: normal;
        font-size: 13px;
        color: #AAAAAA;
      }
      .goods-listing{
        font-weight: 400;
        font-style: normal;
        font-size: 12px;
      }
    }
    .logistics{
      margin-top: 20px;
      p{
        margin: 0;
        padding: 0;
      }
      .logistics-item{
        margin-bottom: 10px;
        .time{
          font-weight: 400;
          font-style: normal;
          font-size: 12px;
          color: #AAAAAA;
          margin-bottom: 5px;
        }
        .text{
          font-size: 14px;
          font-weight: 400;
          font-style: normal;
        }
      }
    }
  }
}
</style>
